define
(
    ["require",
     "lib/knockout"],
    function (require, ko)
    {
        ko.bindingHandlers.shapesBind = 
        {
            init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
            {
                var shapesObservableArray = valueAccessor();

                var updateFunc = function(newArray)
                {
                    var $svg = $(element).find("svg");
                    if (!$svg.length)
                    {
                        return;
                    }

                    $svg.empty();

                    // If objects are grouped then we need to calculate absolute
                    // coordinates by adding left and top of the group
                    var canvas = newArray.length ? newArray[0].getShape().canvas : null;
                    var activeGroup = canvas ? canvas.getActiveGroup() : null;

                    var groupedObjects = {};

                    if (activeGroup)
                    {
                        var objects = activeGroup.getObjects();
                        for (var i = 0; i < objects.length; i++)
                        {
                            groupedObjects[objects[i]] = 1;
                        }
                    }

                    var groupLeft = activeGroup ? activeGroup.left : 0;
                    var groupTop = activeGroup ? activeGroup.top : 0;
                                        
                    for (var i = 0; i < newArray.length; i++)
                    {
                        if (newArray[i].getShape().annotation)
                        {
                            continue;
                        }
                        
                        var shape = newArray[i].getShape().clone();

                        // Images do not correctly render in SVG
                        // TODO: Fix this
                        if (shape instanceof fabric.Image)
                        {
                            continue;
                        }

                        if (groupedObjects[shape])
                        {
                            shape.left = groupLeft + shape.left;
                            shape.top = groupTop + shape.top;
                        }
                        
                        $svg.append(shape.toSVG());
                    }

                    // Refresh svg or else paths won't show up
                    $(element).find(".thumbnail-svg-container").html($(element).find(".thumbnail-svg-container").html());
                };

                shapesObservableArray.subscribe(updateFunc);
                updateFunc(shapesObservableArray());
            }
        };
    }
);